package com.heima.wemedia.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.util.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Resource
    private FileStorageService fileStorageService;


    @Override
    @Transactional
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        try {
            //1.将文件上传到minio
            String postfix = StrUtil.subAfter(multipartFile.getOriginalFilename(), ".", true);
            String fileUrl = StrUtil.format("{}.{}", IdUtil.simpleUUID(), postfix);
            String imgFile = fileStorageService.uploadImgFile(null, fileUrl, multipartFile.getInputStream());

            //2.将数据保存到数据库
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(imgFile);
            wmMaterial.setType(Convert.toShort(0));
            wmMaterial.setUserId(Convert.toInt(WmThreadLocalUtil.getUserId()));
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setIsCollection(Convert.toShort(0));
            this.save(wmMaterial);

            //3.返回数据
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_ERRO);
        }
    }

    @Override
    public PageResponseResult<List<WmMaterial>> findList(WmMaterialDto dto) {

        //1.检查参数
        dto.checkParam();
        //2.分页查询

        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());


        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.lambdaQuery();
        //是否收藏
        lambdaQueryWrapper.eq(ObjectUtil.equal(dto.getIsCollection(), 1), WmMaterial::getIsCollection, dto.getIsCollection());

        //按照用户查询,时间倒序
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUserId())
                .orderByDesc(WmMaterial::getCreatedTime);

        //查询数据
        super.page(page, lambdaQueryWrapper);

        //3.结果返回
        return PageResponseResult.<List<WmMaterial>>builder()
                .currentPage(dto.getPage())
                .size(dto.getSize())
                .total(Convert.toInt(page.getTotal()))
                .data(page.getRecords())
                .build();
    }

    @Override
    public ResponseResult<AppHttpCodeEnum> deleteMaterial(Integer id) {

        //1.判断是否为空
        WmMaterial material = this.lambdaQuery().eq(WmMaterial::getId, id).one();
        if (ObjectUtil.isEmpty(material)) {
            //空数据
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        try {
            //删除
            this.removeById(id);
        } catch (Exception e) {
            //删除失败
            return ResponseResult.errorResult(501, "文件删除失败");
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult<AppHttpCodeEnum> cancelCollect(Integer id) {
        return this.updateIsCollection(id, WemediaConstants.CANCEL_COLLECT_MATERIAL);
    }

    @Override
    public ResponseResult<AppHttpCodeEnum> collect(Integer id) {
        return this.updateIsCollection(id, WemediaConstants.COLLECT_MATERIAL);
    }

    //修改收藏状态
    private ResponseResult<AppHttpCodeEnum> updateIsCollection(Integer id, Short type) {
        //补充修改的数据
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection(type);

        try {
            this.updateById(wmMaterial);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }
}
